/**
 * BBD Service Inc
 * All Rights Reserved @2018
 */
package com.hooview.web.controller;

import com.hooview.api.entity.User;
import com.hooview.api.entity.dto.UserDTO;
import com.hooview.api.service.UserService;
import com.hooview.utils.AjaxMsg;
import com.hooview.utils.AssertUtils;
import com.hooview.utils.Paginator;
import com.hooview.utils.ValidUtil;
import com.hooview.web.template.ExecuteCallBack;
import com.hooview.web.template.ExecuteTemplate;
import me.gavincook.sso.client.annotation.LoginRequired;
import me.gavincook.sso.client.request.ResetPasswordRequest;
import me.gavincook.sso.client.result.CommonResult;
import me.gavincook.sso.client.result.item.UserItem;
import me.gavincook.sso.client.service.SSOService;
import me.gavincook.sso.client.service.impl.SSOServiceImpl;
import me.gavincook.sso.client.thread.SSOPropertiesHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户控制器
 *
 * @author gavincook
 * @version $ID: UserController.java, v0.1 2018-05-31 21:25 gavincook Exp $$
 */
@RestController
@RequestMapping("/users")
@LoginRequired
public class UserController {

    @Autowired
    private ExecuteTemplate executeTemplate;

    @Autowired
    private UserService userService;

    private SSOService ssoService = SSOServiceImpl.getInstance();

    /**
     * 获取当前用户信息
     *
     * @return
     */
    @RequestMapping(value = "/current", method = RequestMethod.GET)
    @ResponseBody
    public AjaxMsg getCurrentInfo() {
        AjaxMsg ajaxMsg = new AjaxMsg();
        executeTemplate.executeWithoutTransaction(() -> {
                    CommonResult<UserItem> result = ssoService.getCurrentUserInfo();
                    if (result != null) {
                        ajaxMsg.setDatas(result.getResult());
                    }
                }
                , ajaxMsg);

        return ajaxMsg;
    }

    /**
     * 登出
     *
     * @return
     */
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    @ResponseBody
    public AjaxMsg logout() {
        AjaxMsg ajaxMsg = new AjaxMsg();
        executeTemplate.executeWithoutTransaction(() -> {
                    ajaxMsg.setDatas(ssoService.logout());
                    SSOPropertiesHolder.setNotLoginHeaderFlag(true);
                }
                , ajaxMsg);

        return ajaxMsg;
    }

    /**
     * 重置当前登录用户密码，传输数据格式为：
     * {@code {
     * oldPassword:xxx,//旧密码
     * newPassword:xxx//新密码
     * }}
     *
     * @param resetPasswordRequest
     * @return
     */
    @RequestMapping(value = "/password", method = RequestMethod.PUT)
    @ResponseBody
    public AjaxMsg resetPassword(@RequestBody ResetPasswordRequest resetPasswordRequest) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        executeTemplate.executeWithoutTransaction(() -> {
                    ajaxMsg.setDatas(ssoService.resetPassword(resetPasswordRequest));
                    //ajaxMsg.setDatas(ssoService.resetCurrentPassword(SSOPropertiesHolder.getTicket(), resetPasswordRequest));
                }
                , ajaxMsg);

        return ajaxMsg;
    }

    @RequestMapping(value = "", method = RequestMethod.GET)
    @ResponseBody
    public AjaxMsg searchUsers(HttpServletRequest request, Integer pageSize, Integer pageNum) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        executeTemplate.executeWithoutTransaction(() -> {
                    Map<String, String[]> parameterMap = request.getParameterMap();
                    Map<String, Object> params = new HashMap<>();
                    for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
                        params.put(entry.getKey(), entry.getValue()[0]);
                    }
                    Map map = userService.queryByParams(params, pageNum, pageSize);
                    ajaxMsg.setDatas(new Paginator<>(Long.valueOf(map.get("total") + ""), (List<UserDTO>) (map.get("users")), Integer.valueOf(map.get("pageNum") + ""), pageSize));
                }
                , ajaxMsg);

        return ajaxMsg;
    }

    /**
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.PUT)
    @ResponseBody
    public AjaxMsg updateUser(@RequestBody User user) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        executeTemplate.executeWithoutTransaction(
                new ExecuteCallBack() {
                    @Override
                    public void check() {
                        AssertUtils.assertNotNull(user, "更新参数为空");
                        AssertUtils.assertNotNull(user.getId(), "更新用户ID为空");
                    }

                    @Override
                    public void service() {
                        User updateUser = new User();
                        updateUser.setId(user.getId());
                        updateUser.setMedia(user.getMedia());
                        updateUser.setMediaType(user.getMediaType());
                        userService.update(updateUser);
                        ajaxMsg.setDatas(true);
                    }
                }
                , ajaxMsg);

        return ajaxMsg;
    }

    /**
     * 获取自媒体用户列表
     *
     * @param pageNum 页码
     * @param pageSize 每页条数
     * @param mediaType 自媒体类型  00：非平台自媒体，01：平台自媒体
     * @param uid 用户id
     * @return
     */
    @RequestMapping(value = "/getMediaUser", method = RequestMethod.GET)
    public AjaxMsg getMediaUser(@RequestParam(defaultValue = "1") Integer pageNum,
                                @RequestParam(defaultValue = "10") Integer pageSize,
                                @RequestParam(required = false) String mediaType,
                                @RequestParam(required = false) String uid) {
        AjaxMsg ajaxMsg = new AjaxMsg();

        executeTemplate.executeWithoutTransaction(() -> {
                    Map<String, Object> params = new HashMap<>();
                    if (!ValidUtil.isEmpty(mediaType)) {
                        params.put("mediaType", mediaType);
                    }
                    Map map = userService.queryMediaUserByParams(params, pageNum, pageSize);
                    ajaxMsg.setDatas(new Paginator<>(Long.valueOf(map.get("total") + ""), (List<User>) (map.get("users")), Integer.valueOf(map.get("pageNum") + ""), pageSize));
                }
                , ajaxMsg);

        return ajaxMsg;
    }

}
